/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.evaluationSystem.controller;

import com.evaluationSystem.annotation.LogOperation;
import com.evaluationSystem.config.R;
import com.evaluationSystem.entity.SecurityUser;
import com.evaluationSystem.entity.SysUserEntity;
import com.evaluationSystem.entity.UserDetail;
import com.evaluationSystem.entity.dto.PasswordDTO;
import com.evaluationSystem.entity.dto.SysMenuDTO;
import com.evaluationSystem.entity.dto.SysUserDTO;
import com.evaluationSystem.enums.MenuTypeEnum;
import com.evaluationSystem.excel.SysUserExcel;
import com.evaluationSystem.excel.SysUserExcel2;
import com.evaluationSystem.password.PasswordUtils;
import com.evaluationSystem.service.ShiroService;
import com.evaluationSystem.service.SysMenuService;
import com.evaluationSystem.service.SysRoleUserService;
import com.evaluationSystem.service.SysUserService;
import com.evaluationSystem.util.ConvertUtils;
import com.evaluationSystem.util.ExcelUtils;
import com.evaluationSystem.util.PageData;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 用户管理
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleUserService sysRoleUserService;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private ShiroService shiroService;

	@GetMapping("page")
	@RequiresPermissions("sys:user:page")
	public R<PageData<SysUserDTO>> page(@RequestParam Map<String, Object> params){
		PageData<SysUserDTO> page = sysUserService.page(params);

		return R.success(page);
	}

	@GetMapping("list")
	@RequiresPermissions("sys:user:list")
	public R<List<SysUserDTO>> list(@RequestParam Map<String, Object> params){
		List<SysUserDTO> list = sysUserService.list(params);

		return R.success(list);
	}

	@GetMapping("edit/{id}")
	@RequiresPermissions("sys:user:info")
	public R<SysUserDTO> get(@PathVariable("id") Long id){
		SysUserDTO data = sysUserService.get(id);

		if (data == null) {
			return R.failed("未找到该用户!");
		}

		//用户角色列表
		List<Long> roleIdList = sysRoleUserService.getRoleIdList(id);
		data.setRoleIdList(roleIdList);

		return R.success(data);
	}

	@GetMapping("info")
	public R<SysUserDTO> info(){
		SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class);
		return R.success(data);
	}

	@PutMapping("changePassword")
	@LogOperation("修改密码")
	public R password(@RequestBody PasswordDTO dto){

		UserDetail user = SecurityUser.getUser();

		//原密码不正确
		if (user.getUsername().equals(dto.getUsername())) {
			if(!PasswordUtils.matches(dto.getPassword(), user.getPassword())){
				return R.failed("账号或密码错误");
			}
		}

		sysUserService.updatePassword(dto.getUsername(), dto.getNewPassword());

		return R.success();
	}

	@PostMapping
	@LogOperation("保存")
	@RequiresPermissions("sys:user:save")
	public R save(@Valid @RequestBody SysUserDTO dto){

		sysUserService.save(dto);

		return R.success();
	}

	@PostMapping("edit")
	@LogOperation("修改")
	@RequiresPermissions("sys:user:update")
	public R update(@Valid @RequestBody SysUserDTO dto){

		sysUserService.update(dto);

		return R.success();
	}

	@DeleteMapping
	@LogOperation("删除")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] ids){

		sysUserService.deleteBatchIds(Arrays.asList(ids));

		return R.success();
	}

	@PostMapping("import")
	@LogOperation("导入")
	@RequiresPermissions("sys:user:import")
	public R imports(HttpServletRequest request) throws Exception {

		List list = ExcelUtils.importExcel(request, SysUserExcel.class);

		List<SysUserEntity> sysUserEntities = ConvertUtils.sourceToTarget(list, SysUserEntity.class);

		return sysUserService.insertBatch(sysUserEntities);
	}

	@GetMapping("export")
	@LogOperation("导出")
	@RequiresPermissions("sys:user:export")
	public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
		String fileName = (String) params.get("fileName");

		params.put("superAdmin", 0);

		List<SysUserDTO> list = sysUserService.list(params);

		for (SysUserDTO sysUserDTO : list) {
			String password = new String(Base64.getDecoder().decode(sysUserDTO.getPassword2()), "UTF-8");
			sysUserDTO.setPassword(password);
		}

		ExcelUtils.exportExcelToTarget(response, fileName, list, SysUserExcel2.class);
	}

	@GetMapping("getUserPermissionByToken")
	public R getUserPermissionByToken() {
		UserDetail user = SecurityUser.getUser();

		Set<String> allPermissions = shiroService.getUserPermissions();
		Set<String> permissions = shiroService.getUserPermissions(user);
		List<SysMenuDTO> menus = sysMenuService.getUserMenuList(user, MenuTypeEnum.MENU.value());

        Map<String, Object> map = new HashMap<>(3);
		map.put("allAuth", allPermissions);
		map.put("auth", permissions);
		map.put("menu", menus);

		return R.success(map);
	}

}
